<script setup lang="ts">
import { ref, onMounted } from "vue";
import { apiGetUserRecord,apiWriteMethod} from "@/apis/apis.js";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useAppStore } from "@/stores/appStore";
const appStore = useAppStore();
const arrChoose = ref<number[]>([])
console.log(appStore.uid);

// 表单数据
const formData = ref({
  recordId: null as number | null,  // 选择的Record ID
  title: "",
  time: new Date().toISOString().slice(0, 16), // 带时间的日期
  phase: "",
  detail: "",
  weather: "晴",
  temperature: "1",
  operator: "",
  extra:"",
  images: [] as string[]
});

// 记录列表
const records = ref<Array<{
  id: number;
  block: string;
  batch: string;
  area: string;
  crop: string;
  methods: {
    phase: string;
  }[];
}>>([]);

// 加载记录列表
const loadRecords = async () => {
  try {
    const res = await apiGetUserRecord({},appStore.uid);
    records.value = res.data.rows;
    arrChoose.value=res.data.rows.map((item:any) => item.id);
    console.log(arrChoose.value);
    console.log(records.value);
  } catch (error) {
    console.error('加载记录失败:', error);
    uni.showToast({ title: '加载记录失败', icon: 'none' });
  }
};

// 图片上传
// 图片上传
const uploadImage = () => {
  uni.chooseImage({
    count: 9,
    success: async (res) => {
      uni.showLoading({ title: '上传中...' });
      for (const filePath of res.tempFilePaths) {
        const uploadRes = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: 'https://www.combinecalculate.cn/api/upload/image', // 服务器上传接口
            filePath,
            name: 'file',
            success: (res) => {
              console.log('上传成功，返回的数据：', res.data); // 输出返回的原始数据，看看内容是什么
              try {
                const data = JSON.parse(res.data); // 尝试解析 JSON
                resolve(data as { url: string });
              } catch (error) {
                reject('无法解析 JSON 响应');
              }
            },
            fail: reject
          });
        });

        // 将返回的 URL 添加到现有的 methodImages 数组中，而不是重置它
        const newUrl = (uploadRes as { url: string }).url;
        formData.value.images.push(newUrl);
        console.log("当前的图片数组:", formData.value.images); // 输出当前的图片数组
      }

      uni.showToast({ title: '上传成功', icon: 'success' });
      uni.hideLoading();
    }
  });
};

// 移除图片
const removeImage = (index: number) => {
  formData.value.images.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
  if (!validateForm()) return;
  
  try {
    uni.showLoading({ title: '提交中...' });    
    
    const res = await apiWriteMethod({
      title: formData.value.title,
      time: formData.value.time,
      detail: formData.value.detail,
      phase: formData.value.phase,
      weather: formData.value.weather,
      temperature: formData.value.temperature,
      operator: formData.value.operator,
      images: formData.value.images,
      extra:formData.value.extra,
      rid: formData.value.recordId, // 关联到选择的record
      state: true
    });
    console.log(res);
    
    if (res.errCode===200) {
      uni.showToast({ title: '操作记录添加成功' });
      setTimeout(() => {
        uni.navigateBack(); // 返回上一页
      }, 1500);
    } else {
      uni.showToast({ title: '提交失败: ' + res.message, icon: 'none' });
    }
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({ title: '提交失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 验证表单
const validateForm = () => {
  if (!formData.value.recordId) {
    uni.showToast({ title: '请选择记录', icon: 'none' });
    return false;
  }
  if (!formData.value.title) {
    uni.showToast({ title: '请填写操作标题', icon: 'none' });
    return false;
  }
  if (!formData.value.detail) {
    uni.showToast({ title: '请填写操作内容', icon: 'none' });
    return false;
  }
  if (!formData.value.operator) {
    uni.showToast({ title: '请填写记录员姓名', icon: 'none' });
    return false; 
  }
  return true;
};
loadRecords();
const setRecord = () => {
  console.log(formData.value.recordId!-1);
  // 查找formData.value.recordId在arrChoose中的索引
  const index = arrChoose.value.indexOf(formData.value.recordId!);

  
  formData.value.phase=records.value[index].methods[0].phase;
}


</script>

<template>
  <view class="form-container">
    <uni-forms>
      <!-- 选择记录 -->
      <uni-section title="记录" type="line">
        <uni-forms-item label="记录" required>
          <uni-data-select
            v-model="formData.recordId"
            :localdata="records.map(r => ({
              value: r.id,
              text: `区块${r.block}-${r.batch} (${r.crop}, ${r.area}亩)`
            }))"
            placeholder="请选择要添加操作的记录"
            @change="setRecord()"
          />
        </uni-forms-item>
      </uni-section>
      
      <!-- 操作信息 -->
      <uni-section title="操作信息" type="line">
        <uni-forms-item label="标题" required>
          <uni-easyinput 
            v-model="formData.title" 
            placeholder="如: 播种、施肥、灌溉等" 
          />
        </uni-forms-item>
        <uni-forms-item label="阶段" >
          <uni-easyinput 
            v-model="formData.phase" 
            placeholder="请输入处于的阶段" 
          />
        </uni-forms-item>
        <uni-forms-item label="操作时间">
          <uni-datetime-picker 
            v-model="formData.time" 
            type="datetime" 
          />
        </uni-forms-item>
        
        <uni-forms-item label="天气">
          <uni-data-select
            v-model="formData.weather"
            :localdata="[
              { value: '晴', text: '晴' },
              { value: '多云', text: '多云' },
              { value: '阴', text: '阴' },
              { value: '雨', text: '雨' },
              { value: '雪', text: '雪' }
            ]"
          />
        </uni-forms-item>
        
        <uni-forms-item label="温度(℃)">
          <uni-easyinput 
            v-model="formData.temperature" 
            placeholder="请输入温度" 
            type="number" 
          />
        </uni-forms-item>
        
        <uni-forms-item label="内容" required>
          <uni-easyinput 
            v-model="formData.detail" 
            placeholder="详细描述操作内容" 
            type="textarea" 
          />
        </uni-forms-item>
        <uni-forms-item label="额外" >
          <uni-easyinput 
            v-model="formData.extra" 
            placeholder="额外补充信息" 
           
          />
        </uni-forms-item>
        
        <uni-forms-item label="记录员">
          <uni-easyinput required
            v-model="formData.operator" 
            placeholder="请输入记录员姓名" 
          />
        </uni-forms-item>
        
        <uni-forms-item label="现场照片">
          <view class="image-uploader">
            <view 
              v-for="(img, index) in formData.images" 
              :key="index" 
              class="image-preview"
            >
              <image :src="img" mode="aspectFill" @click="previewImage(img, formData.images)" />
              <uni-icons 
                type="close" 
                @click="removeImage(index)" 
              />
            </view>
            <view 
              v-if="formData.images.length < 9" 
              class="upload-btn" 
              @click="uploadImage"
            >
              <uni-icons type="plusempty" size="24" />
              <text>添加照片</text>
            </view>
          </view>
        </uni-forms-item>
      </uni-section>
      
      <view class="form-actions">
        <button type="primary" @click="submitForm">提交操作记录</button>
      </view>
    </uni-forms>
  </view>
</template>

<style scoped lang="scss">
.form-container {
  padding: 30rpx;
  
  .image-uploader {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    
    .image-preview {
      position: relative;
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      overflow: hidden;
      
      image {
        width: 100%;
        height: 100%;
      }
      
      .uni-icons {
        position: absolute;
        top: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 6rpx;
        border-radius: 0 0 0 8rpx;
      }
    }
    
    .upload-btn {
      width: 160rpx;
      height: 160rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px dashed #ddd;
      border-radius: 8rpx;
      color: #999;
      
      text {
        font-size: 24rpx;
        margin-top: 10rpx;
      }
    }
  }
  
  .form-actions {
    margin-top: 40rpx;
    
    button {
      width: 100%;
    }
  }
}
</style>